package com.lukebang.service.serviceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lukebang.constant.Const;
import com.lukebang.constant.PayMethod;
import com.lukebang.constant.TypeOfIndent;
import com.lukebang.dao.CityCostRuleDAO;
import com.lukebang.dao.CustomerAddressDAO;
import com.lukebang.dao.MeasureIndentDAO;
import com.lukebang.dao.MerchantDAO;
import com.lukebang.dao.MerchantsWalletRecordDAO;
import com.lukebang.dao.TerritoryDAO;
import com.lukebang.dao.WorkerDao;
import com.lukebang.dao.WorkerWalletRecordDao;
import com.lukebang.pojo.CityCostRule;
import com.lukebang.pojo.CustomerAddress;
import com.lukebang.pojo.Indent;
import com.lukebang.pojo.MeasureIndent;
import com.lukebang.pojo.Merchant;
import com.lukebang.pojo.MerchantsWalletRecord;
import com.lukebang.pojo.Worker;
import com.lukebang.pojo.WorkerWalletRecord;
import com.lukebang.service.IInstallIndentService;
import com.lukebang.service.IMeasureIndentService;
import com.lukebang.util.DateUtils;
import com.lukebang.util.LuKeOrderNoUtil;
import com.lukebang.util.ClothCurtain.Arith;

/**
 * 
 * MeasureIndentServiceImpl 上午11:16:13
 * 
 * Copyright zhaocj Inc. All rights reserved. Love ME Like Justin Bieber.
 */
@Service("measureIndentSER")
public class MeasureIndentServiceImpl implements IMeasureIndentService {
	private static Logger logger = LogManager.getLogger(MeasureIndentServiceImpl.class.getName());

	@Resource
	CustomerAddressDAO customerAddressDAO;
	@Resource
	CityCostRuleDAO cityCostRuleDAO;
	@Resource
	MeasureIndentDAO measureIndentDAO;
	@Resource
	TerritoryDAO territoryDAO;
	@Resource
	private IInstallIndentService installIndentSER;
	@Resource
	private MerchantDAO  merchantDAO;
	@Resource
	private MerchantsWalletRecordDAO merchantsWalletRecordDAO;
	@Resource
	private WorkerDao workerDao;
	@Resource
	private WorkerWalletRecordDao workerWalletRecordDao;
	

	@Override
	public String payMoneyForAlipay(HttpServletRequest request, Double addPrice, Integer indentId, Integer relievedBao,
			Integer type, Integer motorNum, Double money) {
		return null;
	}

	@Override
	public MeasureIndent selectByPrimaryKey(Object indentID) {
		return measureIndentDAO.selectByPrimaryKey(indentID);
	}

	@Override
	public Map<String, Object> selectMeasureIndentByMerchant(HttpSession session, String customerName,
			String customerPhone, String indentID, String subscribeTimeBegin, String subscribeTimeEnd,
			String beginTimeBegin, String beginTimeEnd, Integer indentStatus, Integer offset, Integer limit,
			String sort, String order) {
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		Map<String, Object> retsMap = new HashMap<String, Object>();
		retsMap.put("total", 0);
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("offset", offset);
		queryMap.put("limit", limit);
		queryMap.put("sort", sort);
		queryMap.put("order", order);
		queryMap.put("customerName", customerName);
		queryMap.put("customerPhone", customerPhone);
		queryMap.put("indentID", indentID);
		queryMap.put("subscribeTimeBegin", subscribeTimeBegin);
		queryMap.put("subscribeTimeEnd", subscribeTimeEnd);
		queryMap.put("beginTimeBegin", beginTimeBegin);
		queryMap.put("beginTimeEnd", beginTimeEnd);
		queryMap.put("indentStatus", indentStatus);
		queryMap.put("merchantID", merchant.getMerchantsId());
		List<MeasureIndent> beans = measureIndentDAO.selectMeasureIndentByMerchant(queryMap);
		retsMap.put("total", measureIndentDAO.selectMeasureIndentCountByMerchant(queryMap));
		retsMap.put("rows", beans);
		return retsMap;
	}

	@Override
	public Integer insertMeasureIndent(HttpServletRequest request, String phone, String name, Integer roomNumber,
			String address, String province, String city, String country, String orderTime, String remark,
			HttpSession session) {
		// 得到登陆的商户的信息
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		// 根据传送过来的code 转化成对应的省和市和城镇
		List<String> areaNames = territoryDAO.selectForConvertCodeToAreaName(province, city, country);
		CustomerAddress customerAddress = new CustomerAddress();
		customerAddress.setAddress(address);
		customerAddress.setProvince(areaNames.get(0));
		customerAddress.setCity(areaNames.get(1));
		customerAddress.setArea(areaNames.get(2));
		customerAddress.setAreaCode(country);
		customerAddress.setName(name);
		customerAddress.setPhone(phone);
		customerAddress.setCuAddressCodeStr(province + "/" + city);
		customerAddressDAO.insertCustomerAddress(customerAddress);
		// 正式插入订单信息
		MeasureIndent indent = new MeasureIndent();
		// '订单类型0测量 1安装 2维修 3经销商自主测量的',
		indent.setType(0);
		indent.setStatus(4);
		indent.setRoomNumB(roomNumber);
		// 是谁下的订单
		indent.setCustomerId(merchant.getMerchantsId());
		// 订单产生时间
		indent.setBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		// 订单预约的时间
		indent.setSubscribeTime(orderTime);
		// 代表是商家或者个人下的订单 有利于后面的统计
		indent.setIndentType(3);
		indent.setCuAdId(customerAddress.getCuAdId());
		indent.setCustomerId(merchant.getMerchantsId());
		indent.setRemark(remark);
		/**
		 * 查询出商人和工人不同的订花费规则
		 */
		CityCostRule cityCostRuleForMerchant = cityCostRuleDAO.selectCostRuleByCityCode(province + "/" + city, 0);
		CityCostRule cityCostRuleForWorker = cityCostRuleDAO.selectCostRuleByCityCode(province + "/" + city, 1);
		Double indentPrice = 0.0;
		Double merchantsPrice = 0.0;
		if (cityCostRuleForMerchant.getMeaBaseNum() >= Integer.valueOf(roomNumber)) {// 测量房间数和该地区规定的测量房间数比较
			merchantsPrice = Arith.add((Double) cityCostRuleForMerchant.getMeaStartingFare(), merchantsPrice);
			indentPrice = Arith.add((Double) cityCostRuleForWorker.getMeaStartingFare(), indentPrice);
		} else if (cityCostRuleForMerchant.getMeaBeyondNumTwo() >= roomNumber
				&& roomNumber > cityCostRuleForMerchant.getMeaBeyondNumOne()) {
			merchantsPrice = Arith
					.add(Arith
							.add((Double) cityCostRuleForMerchant.getMeaStartingFare(),
									(roomNumber - (Integer) cityCostRuleForMerchant.getMeaBaseNum())
											* (Double) cityCostRuleForMerchant.getMeaBeyUnitPriceOne()),
							merchantsPrice);
			indentPrice = Arith.add(Arith.add((Double) cityCostRuleForWorker.getMeaStartingFare(),
					(roomNumber - (Integer) cityCostRuleForWorker.getMeaBaseNum())
							* (Double) cityCostRuleForWorker.getMeaBeyUnitPriceOne()),
					indentPrice);
		} else {
			// 第一价格区间计算价格
			Double merchantsPrice0 = Arith.add(
					Arith.add((Double) cityCostRuleForMerchant.getMeaStartingFare(),
							(cityCostRuleForMerchant.getMeaBeyondNumTwo()
									- (Integer) cityCostRuleForMerchant.getMeaBaseNum())
									* (Double) cityCostRuleForMerchant.getMeaBeyUnitPriceOne()),
					merchantsPrice);
			Double indentPrice0 = Arith.add(Arith.add((Double) cityCostRuleForWorker.getMeaStartingFare(),
					(cityCostRuleForWorker.getMeaBeyondNumTwo() - (Integer) cityCostRuleForWorker.getMeaBaseNum())
							* (Double) cityCostRuleForWorker.getMeaBeyUnitPriceOne()),
					indentPrice);
			// 第二价格区间计算价格
			merchantsPrice = Arith.add((roomNumber - cityCostRuleForMerchant.getMeaBeyondNumTwo())
					* (Double) cityCostRuleForMerchant.getMeaBeyUnitPriceTwo(), merchantsPrice0);
			indentPrice = Arith.add((roomNumber - cityCostRuleForWorker.getMeaBeyondNumTwo())
					* (Double) cityCostRuleForWorker.getMeaBeyUnitPriceTwo(), indentPrice0);
		}
		
		indent.setMerchantsPrice(merchantsPrice);
		indent.setMerchantsRealPrice(merchantsPrice);
		indent.setIndentPrice(indentPrice);
		indent.setWorkerRealPrice(indentPrice);
		indent.setIndentSource(1);
		measureIndentDAO.insertMeasureIndent(indent);
		return indent.getIndentId();
	}

	@Override
	public boolean modifyForPayMeasureIndent(HttpServletRequest request, Integer indentID, Double addPrice,
			Integer relievedBao, HttpSession session) {
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		MeasureIndent measureIndent = (MeasureIndent) measureIndentDAO.selectByPrimaryKey(indentID);
		if (relievedBao == null) {
			relievedBao = 0;
		}
		Double needPayMoney = measureIndent.getMerchantsPrice() + addPrice;
		if (relievedBao == 1) {
			needPayMoney = needPayMoney + 5;
		}
		logger.error("+++++++++++++++++++++++需要测量订单付款的总价格：{}++++++++++++++++++++++++++++", needPayMoney);
		String lukebang_order_num = LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
				PayMethod.ALIPAY.getIndex(), TypeOfIndent.MEASURE.getIndex());
		request.setAttribute("lukebang_tradeno", lukebang_order_num);
		request.setAttribute("lukebang_subject", "测量订单");
		request.setAttribute("lukebang_total_fee", String.valueOf(needPayMoney));
		request.setAttribute("lukebang_body", "测量订单付款");
		request.setAttribute("lukebang_returnUrl", "http://lukebang.com.cn/lukebang/indent/addMeasure.htm");
		Map<String, String> extraMap = new HashMap<String, String>();
		extraMap.put("bussType", TypeOfIndent.MEASURE.getName());
		extraMap.put("indent", String.valueOf(indentID));
		extraMap.put("relievedBao", String.valueOf(relievedBao));
		extraMap.put("addPrice", String.valueOf(addPrice));
		extraMap.put("originalMerchantPrice", String.valueOf(measureIndent.getMerchantsPrice()));
		extraMap.put("originalIndentPrice", String.valueOf(measureIndent.getIndentPrice()));
		request.setAttribute("extra_common_param", JSON.toJSONString(extraMap, SerializerFeature.UseSingleQuotes));
		/**
		 * 添加钱包的日志记录 添加钱包的日志记录 添加钱包的日志记录
		 */
		MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
		merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
		merchantsWalletRecord.setIndentId(indentID);
		merchantsWalletRecord.setType(0);
		merchantsWalletRecord.setOrderNo(lukebang_order_num);
		merchantsWalletRecord.setMainMoney(measureIndent.getMerchantsPrice());
		merchantsWalletRecord.setAddMoney(addPrice);
		merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
		return false;
	}

	@Override
	public Map<String,Object> toInstallIndent(HttpServletRequest request, HttpSession session, Integer mesureIndentId) {
		// TODO Auto-generated method stub
		//得到测量单信息
		Map<String,Object> map=new HashMap<>();
		MeasureIndent measureIndent=measureIndentDAO.selectByPrimaryKey(mesureIndentId);
		if(mesureIndentId==null){
			map.put("status", "1");
			map.put("message", "测量单不存在 ...");
			return map;
		}
		if(measureIndent.getStatus() != 2){//测量单未完成，不能转安装
			map.put("status", "2");
			map.put("message", "测量还未完成 ... ");
			return map;
		}
		CustomerAddress customerAddress=customerAddressDAO.selectCustomerAddress(mesureIndentId);
		//生成安装单
		if(customerAddress !=null){
			request.setAttribute("toInstall", "1");
			installIndentSER.insertInstallIndent(request, customerAddress.getPhone(), customerAddress.getName(), "测量单一键转安装单", 
					customerAddress.getAddress(), territoryDAO.selectCodeByName(customerAddress.getProvince()), 
					territoryDAO.selectCodeByName(customerAddress.getCity()), 
					customerAddress.getAreaCode(), DateUtils.getDate("yyyy-MM-dd HH:mm:ss"), 
					0, null, null, null, null, null, String.valueOf(mesureIndentId), session);
		}
			System.out.println("===================已经生成订单=========================");
			
		//声明测量单为已申请安装
		measureIndent.setIsInstalled(1);
		int rows=measureIndentDAO.modifyByPrimaryKey(measureIndent);
		if(rows>0){
			map.put("status", "0");
			map.put("message", "转安装单成功");
		}else{
			map.put("status", "3");
			map.put("message", "转安装单失败");
		}
		return map;
	}

//	@Override
//	public Map<String, Object> quitIndent(HttpServletRequest request, HttpSession session, Integer type,Integer mesureIndentId) {
//		// TODO Auto-generated method stub
//		Map<String,Object> map=new HashMap<>();
//		// 1.获取测量单信息
//		MeasureIndent indent=measureIndentDAO.selectByPrimaryKey(mesureIndentId);
//		if(indent==null){
//			map.put("status", "1");
//			map.put("message", "订单不存在 ...");
//			return map;
//		}
//		// 扣款金额
//		Double subMoney = 0.0;
//		//给予工人的补助
//		Double toWorker=0.0;
//		//商家的钱包
//		Double toMerchant=0.0;
//		
//		//1.所有交易记录
//				Double totalFee=0.0;
//				Map<String,Object> param=new HashMap<>();
//				param.put("indentId", mesureIndentId);//测量单号
//				param.put("merchantsType", 0);//交易人身份--商家
//				param.put("merchantsId", indent.getCustomerId());//交易人id
//				param.put("status", 1);//交易状态
//				
//				List<MerchantsWalletRecord> recordList=merchantsWalletRecordDAO.selectMerchantWalletRecords(param);
//				for(MerchantsWalletRecord record:recordList){
//					totalFee+=record.getFinalLostMoney();
//				}
//				if(totalFee >0){
//					//2.处罚规则
//					Map<String, Double> punishMap = cityCostRuleDAO.selectRules(mesureIndentId);
//					//商家信息
//					Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
//					
//					switch (indent.getStatus()) {
//						case 0:  //等待工人接单---取消订单,并退还全款
//								toMerchant=totalFee;
//							break;
//						case 1:  //已接单---取消订单，并罚款
//							if(punishMap !=null){
//								subMoney = punishMap.get("punishWorker");//处罚的钱
//								toMerchant = Arith.sub(totalFee, subMoney);//退还给商家的钱
//								toWorker =  punishMap.get("punishWorker");// 补给工人对的钱
//							}
//							break;	
//						case 5: 	//工人已出发--取消订单，并罚款
//							if(punishMap !=null){
//								subMoney = punishMap.get("punishClient");
//								toMerchant = Arith.sub(totalFee, subMoney);
//								toWorker = punishMap.get("punishClient");
//							}
//							break;	
//						case 4:   //未付款---取消订单就Ok
//						case 2: 	//已完成  --取消订单就ok
//							break;	
//						default:  
//							System.out.println("其他状态的测量单暂不支持取消功能 ...  ...");
//							break;
//					}
//					if(toMerchant !=0.0){
//						if(merchant != null){
//							Map<String,Object>paras=new HashMap<>();
//							paras.put("merchantsId", merchant.getMerchantsId());
//							paras.put("wallet", toMerchant+merchant.getWallet());
//							merchantDAO.updateMerchantWallet(paras);
//						}
//						//做交易记录
//						MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
//						merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
//						merchantsWalletRecord.setIndentId(mesureIndentId);
//						merchantsWalletRecord.setOrderNo(LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
//								PayMethod.BALABCEPAY.getIndex(), TypeOfIndent.MEASURE.getIndex()));
//						merchantsWalletRecord.setType(TypeOfIndent.MEASURE.getIndex());
//						merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
//						merchantsWalletRecord.setSubMoney(subMoney);
//						merchantsWalletRecord.setFinalLostMoney(subMoney);//罚款金额
//						merchantsWalletRecord.setFinalGetMoney(toMerchant);//退还金额
//						merchantsWalletRecord.setStatus(1);
//						merchantsWalletRecord.setRemark("商家取消订单，违约罚款金额");
//						merchantsWalletRecord.setMethod(PayMethod.BALABCEPAY.getMethod());
//						merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
//					}
//					if(toWorker !=0.0){
//						Worker worker = workerDao.selectWorker(indent.getWorkerId());
//						if(worker !=null){
//							Map<String,Object>paras=new HashMap<>();
//							paras.put("workerId", worker.getWorkerId());
//							paras.put("wallet", toWorker+worker.getWallet());
//							workerDao.updateWalletComple(paras);	
//						}
//						//做交易记录
//						WorkerWalletRecord workerWalletRecord=new WorkerWalletRecord();
//						workerWalletRecord.setWorkerId(worker.getWorkerId());
//						workerWalletRecord.setIndentId(mesureIndentId);
//						workerWalletRecord.setFinalGetMoney(toWorker);
//						workerWalletRecord.setOrderNo(LuKeOrderNoUtil.getMerchantsOrderNo(worker.getWorkerId(),
//								PayMethod.BALABCEPAY.getIndex(), TypeOfIndent.MEASURE.getIndex()));
//						workerWalletRecord.setType(8);
//						workerWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
//						workerWalletRecord.setStatus(1);
//						workerWalletRecord.setRemark("商家取消订单，工人获取补助");
//						workerWalletRecord.setMethod(PayMethod.BALABCEPAY.getMethod());
//						workerWalletRecordDao.insertWorkerWalletRecord(workerWalletRecord);
//					}
//					//修改订单状态
//					indent.setIsDelete(1);
//					measureIndentDAO.modifyByPrimaryKey(indent);
//					map.put("status", "0");
//					map.put("message", "订单取消成功... ");
//					return map;
//				}
//				map.put("status", "2");
//				map.put("message", "订单取消失败... ");
//				return map;
//	}

	
}
